window.onload = function () {
	const myCanvas = document.querySelector('.my-canvas');
	const prize = document.querySelector('.prize');
	const ctx = myCanvas.getContext('2d');
	let prizes = ['一等奖', '二等奖', '三等奖', '安慰奖', '谢谢参与'];

	// 随机出奖
	const prizeRandom = () => {
		const chance = Math.random() - 0.9;
		let index = 0;
		if (chance >= 0) {
			return 0;
		}
		else if (chance >= -0.15) {
			return 1;
		}
		else if (chance >= -0.3) {
			return 2;
		}
		else if (chance >= -0.45) {
			return 3;
		}
		else {
			return 4;
		}
	};
	prize.textContent = prizes[prizeRandom()];

	// 填充覆盖颜色
	ctx.fillStyle = '#ddd';
	ctx.fillRect(0, 0, myCanvas.width, myCanvas.height);

	// 鼠标移动(鼠标经过时，保留不重合部分的颜色)
	const mousemove = e => {
		ctx.globalCompositeOperation = 'destination-out';
		ctx.beginPath();
		ctx.arc(e.offsetX, e.offsetY, 30, 0, Math.PI * 2);
		ctx.fill();
		const { data: colors } = ctx.getImageData(0, 0, myCanvas.width, myCanvas.height);
		console.log(colors);
		let count = 0;
		for (let i = 0; i < colors.length; i += 4) {
			if (colors[i + 3] === 0) {	// 获取透明度的值
                count ++;
            }
		}
		if (count > colors.length / 4 * 0.8) {
            myCanvas.width = myCanvas.width;
        }
	};

	myCanvas.addEventListener('mousedown', e => {
		myCanvas.addEventListener('mousemove', mousemove, false);
	}, false);

	myCanvas.addEventListener('mouseup', e => {
		myCanvas.removeEventListener('mousemove', mousemove);
	}, false);
};